<?php

namespace App\Repository;
use App\Model\UserModel;

/**
 * 用户数据仓储数据类
 *
 * @author WangBin
 */
class UserRepo extends BaseRepo
{
    /**
     * 根据手机号查询用户
     *
     * @param string $mobile
     * @return \Hyperf\Database\Model\Builder|\Hyperf\Database\Model\Model|object|null
     */
    public function getByMobile(string $mobile)
    {
        return UserModel::query()->where('mobile', $mobile)->first();
    }

    /**
     * 根据用户名查询用户
     *
     * @param string $loginName
     * @return \Hyperf\Database\Model\Builder|\Hyperf\Database\Model\Model|object|null
     */
    public function getByLoginName(string $loginName)
    {
        return UserModel::query()->where('login_name', $loginName)->first();
    }

    /**
     * 保存用户信息
     *
     * @param array $data
     * @param int $userId
     * @return \Hyperf\Utils\HigherOrderCollectionProxy|\Hyperf\Utils\HigherOrderTapProxy|int|mixed|void
     */
    public function save(array $data, int $userId = 0)
    {
        $query = $userId ? UserModel::find($userId) : new UserModel();
        foreach ($data as $field => $value) {
            $query->{$field} = $value;
        }
        return $query->save() ? $query->id : 0;
    }

    /**
     * 根据用户 id 查询用户
     *
     * @param int $userId
     * @return \Hyperf\Database\Model\Builder|\Hyperf\Database\Model\Model|object|null
     */
    public function getById(int $userId, array $column = ['*'])
    {
        return UserModel::query()
            ->select($column)
            ->where('id', $userId)
            ->first();
    }
}